package com.sys.servlet;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.sys.entity.User;
import com.sys.exception.LoginException;
import com.sys.pojo.JsonResult;
import com.sys.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login.do")
public class LoginServlet extends HttpServlet {

    public LoginServlet() {
        System.out.println("实例化 "+this.getClass().getSimpleName());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 向浏览器返回数据
        PrintWriter writer = resp.getWriter();

        // 先清空user数据
        HttpSession session = req.getSession();
        session.removeAttribute("user");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService userService = new UserService();


        JsonResult jr = new JsonResult();
        try {

            User user = userService.login(username, password);
            // 登录成功后，将用户信息保存到 session中
            session.setAttribute("user",user);

            jr.setCode(0);
            jr.setMsg("登录成功！");

        } catch (LoginException e){
            jr.setCode(100);
            jr.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            jr.setCode(500);
            jr.setMsg("操作发生错误！");
        }
        //将java对象，转换成 json 格式的字符串
        ObjectMapper om=new ObjectMapper();
        String json=om.writeValueAsString(jr);
        writer.write(json);
        writer.close();//关闭
    }
}
